package com.firewolf.rabbitmq;

import java.io.IOException;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import utils.ConnectionUtils;

public class Receiver3 {

	private static final String QUEUE_NAME = "publish_subscribe_queue2";

	private static final String EXCHANGE_NAME = "publish_subscribe_exchange";

	public static void main(String[] args) throws Exception {

		Connection conn = ConnectionUtils.getMQConnection();

		final Channel channel = conn.createChannel();

		// 声明交换机
		channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);

		// 把队列绑定到交换机
		channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "");

		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
					throws IOException {
				try {
					String msg = new String(body);
					System.out.println("Receiver[3]:" + msg);
					Thread.sleep(500);
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					channel.basicAck(envelope.getDeliveryTag(), false);
				}
			}
		};
		channel.basicConsume(QUEUE_NAME, false, consumer);
	}
}
